package com.study.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.study.constant.MessageConstant;
import com.study.constant.RedisMessageConstant;
import com.study.entity.Result;
import com.study.pojo.Order;
import com.study.service.OrderService;
import com.study.utils.SMSUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import java.util.Map;

@RestController
@RequestMapping(value = "/order")
public class OrderController {

    @Reference
    private OrderService orderService;
    @Resource(name = "jedisPool")
    private JedisPool jedisPool;

    @RequestMapping("/findById")
    public Result findById(Integer id){
        try{
            Map<String,Object> map = orderService.findById(id);
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
    }

    @RequestMapping(value = "/submit")
    public Result submit(@RequestBody Map map){
        Result result = null;
        String randomCode = jedisPool.getResource().get(map.get("telephone") + RedisMessageConstant.SENDTYPE_ORDER);
        String validateCode = (String) map.get("validateCode");
        if(randomCode == null || !randomCode.equals(validateCode) ){
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

        map.put("orderType",Order.ORDERTYPE_WEIXIN);
        result = orderService.submit(map);
        if(result.isFlag()){
            String orderDate = (String) map.get("orderDate");
            try {
                SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE, (String) map.get("telephone"),orderDate);
            } catch (ClientException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
